import os

import cv2
from flask import Flask, request, flash, redirect, render_template, Response, jsonify
from hyperlpr import HyperLPR_PlateRecogntion
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['SECRET_KEY'] = '123456'
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
UPLOAD_FOLDER = os.path.join(BASE_DIR, 'uploads')


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('请先选择文件')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            flash('请先选择文件')
            return redirect(request.url)
        if file:
            uploadname = secure_filename(file.filename)
            make_dir(UPLOAD_FOLDER)
            path = os.path.join(UPLOAD_FOLDER, uploadname)
            file.save(path)
            # 读入图片
            image = cv2.imread(path)
            # 识别结果
            reses = HyperLPR_PlateRecogntion(image)
            if len(reses) > 0:
                res = reses.pop(0)
                # flash(res.pop(0))
                # return redirect(request.url)
                return render_template('upload.html', carno=res.pop(0), filename=uploadname)
            # flash("大土豆去了皮 识别失败 OTATO ")
            #             # return redirect(request.url)
            return render_template('upload.html', carno="大土豆去了皮 识别失败 OTATO", filename=uploadname)
    return render_template('upload.html')


def make_dir(make_dir_path):
    path = make_dir_path.strip()
    if not os.path.exists(path):
        os.makedirs(path)


@app.route('/lpr', methods=['POST'])
def lpr():
    file = request.files['file']
    uploadname = secure_filename(file.filename)
    make_dir(UPLOAD_FOLDER)
    path = os.path.join(UPLOAD_FOLDER, uploadname)
    file.save(path)
    # 读入图片
    image = cv2.imread(path)
    reses = HyperLPR_PlateRecogntion(image)
    if len(reses) > 0:
        res = reses.pop(0)
        return jsonify({'carNo': res.pop(0), 'code': 0, 'msg': '操作成功'})
    return jsonify({'code': 500, 'msg': '识别失败'})


@app.route('/image/<filename>/')
def image(filename=None):
    if filename:
        path = os.path.join(UPLOAD_FOLDER, filename)
        file = open(path, 'rb')
        return Response(file.read(), mimetype='image/jpeg')


if __name__ == '__main__':
    app.run(host='0.0.0.0', port='5000')
